const cheerio = require('cheerio')
const galleryPreviewSetParser = require('./galleryPreviewSetParser')

const galleryDetailParser = (body) => {
  let $ = cheerio.load(body)
  let galleryDetail = {
    basic_info: {},
    tags_group: [],
    gallery_thumb: []
  }
  try {
    galleryDetail.gallery_thumb = galleryPreviewSetParser(body)
    galleryDetail.basic_info.title = $('#gn').text()
    if (!galleryDetail.basic_info.title) {
      throw new Error('DETAILPARSEFAIL')
    }
    galleryDetail.basic_info.thumb = $('#gd1>div').css('background').split('url(')[1].split(')')[0]
    galleryDetail.basic_info.jpn_title = $('#gj').html()
    galleryDetail.basic_info.category = $('#gdc').find('a').attr('href').split('/')[3]
    galleryDetail.basic_info.uploader = $('#gdn').find('a').html()
    galleryDetail.basic_info.pageNumber = parseInt($('.ptt td').eq(-2).find('a').html())
    $('#gdd tr').each(function (i, elem) {
      galleryDetail.basic_info[$(this).find('.gdt1').html().replace(':', '')] = $(this).find('.gdt2').text()
    })
    galleryDetail.basic_info.rating = parseFloat($('#rating_label').html().replace('Average:', ''))
    galleryDetail.basic_info.rating_count = $('#rating_count').html()
    $('#taglist table').find('tr').each(function (i, elem) {
      galleryDetail.tags_group.push({type: $(this).find('.tc').html().replace(':', ''), tags: []})
      $(this).find('td').eq(-1).find('div a').each(function (_i, _elem) {
        galleryDetail.tags_group[i]['tags'].push($(this).html())
      })
    })
  } catch (err) {
    throw new Error(err.message)
  }
  return galleryDetail
}

module.exports = galleryDetailParser
